<!-- 首页 -->
<template>
  <div class="home" @scroll='setScrollTop($event)'>
    <div class="Update" v-show="updateShow">
      <div class="content">
        <img src="../image/banben.png" alt="">
        <div class="progress" v-if="barWidth>0">
          <div class="bar" :style="{width: barWidth+'%'}"></div>
          <div style="margin-top: 13px;text-align: center;">更新中{{barWidth}}%</div>
          <div style="margin-top: 13px;text-align: center;font-size:11px;color: rgba(102, 102, 102, 0.75)">(正在更新中...请不要返回或退出)</div>
        </div>
        <div class="progress1" v-if="barWidth<=0">
          <div>页面优化，更快捷更方便</div>
        </div>
        <div class="down" @click="download()">立即更新版本</div>
      </div>
      <img src="../image/delbb.png" alt="" style="position: absolute;
        bottom: 18%;" @click.false="updateShow=false">
    </div>
    <!--  支付类型选择 -->
    <div class='mc' v-show='isdocType' @click.stop='isdocType=false'>
      <div class='duration' @click.stop='isdocType=true'>
        <div class='top'>
          <a @click.stop='isdocType=false'>取消</a>
          <a @click.stop='sureDocType'>确定</a>
        </div>
        <mt-picker :slots="slotsDocType" :valueKey="'numbering'?'numbering':''" @change="onValuesChangeDocType"></mt-picker>
      </div>
    </div>
    <div class="search">
      <div class="icon-logo">
        <img src="../image/logo.png" alt="">
      </div>
      <div class="search-border" @click='goSearch'>
        <img src="../image/icon_search.png" alt="">
        <span>请输入课程名称搜索</span>
      </div>
    </div>
    <!--swiper-->
    <mt-loadmore :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" ref="loadmore" :bottom-pull-text="bottomPullText"
      :autoFill="false">
      <div class="swiper-container" id="swiper1">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for='(item,index) in swiperImg' :key='index'>
            <img :src="item.img_url" />
          </div>
        </div>
        <div class="swiper-pagination"></div>
      </div>

      <!--三个区-->
      <!-- 仅医生可看 -->
      <div class="three-areas" v-if='isLogin&&usertype!="clinic"'>
        <a class="one-area" @click='goImDoctor'>
          <img src="../image/h1.png" alt="">
          <div>
            <div class="english">RESERVATION</div>
            <div class="chinese">智能诊室</div>
          </div>
        </a>
        <router-link to='liveZone' class="one-area">
          <img src="../image/h2.png" alt="">
          <div>
            <div class="english">VIDEO</div>
            <div class="chinese">课程专区</div>
          </div>

        </router-link>

        <a class="one-area" @click='goDocConsultation'>
          <img src="../image/h3.png" alt="">
          <div>
            <div class="english">OUTPATIENT</div>
            <div class="chinese">专家会诊</div>
          </div>

        </a>
        <router-link :to="{name: 'appointmentTime',query: {user:'doctor'}}" class="docterRoom one-area">
          <img src="../image/h4.png" alt="">
          <div>
            <div class="english">CONSULT</div>
            <div class="chinese">患者管理</div>
          </div>

        </router-link>
      </div>
      <!-- 仅医生end -->

      <!-- 仅诊室 -->
      <div class="three-areas" v-if='isLogin&&usertype=="clinic"'>
        <router-link to="ImClinic" class="docterRoom one-area">
          <img src="../image/h1.png" alt="">
          <div>
            <div class="english">OPERATOR</div>
            <div class="chinese">客服管理</div>
          </div>
        </router-link>
        <router-link to='clinicAllEquip' class="one-area">
          <img src="../image/h2.png" alt="">
          <div>
            <div class="english">EQUIPMENT</div>
            <div class="chinese">设备管理</div>
          </div>
        </router-link>
        <router-link to='docOrder?user=clinic' class="one-area">
          <img src="../image/h3.png" alt="">
          <div>
            <div class="english">ORDER</div>
            <div class="chinese">订单管理</div>
          </div>
        </router-link>
        <router-link :to="{name: 'appointmentTime',query: {user:'clinic'}}" class="one-area">
          <img src="../image/h4.png" alt="">
          <div>
            <div class="english">CONSULT</div>
            <div class="chinese">患者管理</div>
          </div>

        </router-link>
      </div>
      <!--热门视频标题-->
      <div class="hot-video-title">
        <img src="../img/head.png" alt="">
      </div>
      <div>
        <ul class="hot-video-list">
          <div class='mc1' v-if="list.length<1">
            <p>暂无数据!</p>
          </div>
          <li v-for='(item,index) in list' :key='index' v-if="list.length>0">
            <a @click=goNext(item)>
              <div class="hot-video-cover-box">
                <img :src="item.course_pic" />
              </div>
              <div style="
                margin-left:1.2rem;">
                <ul style="position: relative;height:1.1rem;display: flex;padding-bottom: 7px;flex-direction: column;justify-content: space-between;">
                  <li style="font-size: 14px;color: #8d8d8d;padding-top: 0.1rem;">{{item.course_name}}</li>
                  <li style="font-size: 9px;color:rgba(0,0,0,0.3);margin:0.03rem 0rem 0.08rem">主讲老师：{{item.teacher_name}}</li>
                  <li style="font-size: 9px;color:rgba(0,0,0,0.2); margin-bottom: 0.05rem;">
                    {{item.starttime}}2018-01-25</li>
                  <li>
                    <span class="discount" v-if='item.iffree == "charge"' style="background: #fbc707;color: #523628"><b>￥</b>{{item.charge}}</span>
                    <span class="discount" v-if='item.iffree == "free"' style="background: #52422b;color: #fdd619;letter-spacing: 3px;">免费</span>
                  </li>
                </ul>
              </div>
              <!-- </router-link> -->
            </a>
          </li>
        </ul>
      </div>
    </mt-loadmore>


  </div>



</template>

<script>
  export default {
    data() {
      return {
        isdocType: false, //是否显示就诊类型选择
        // order_num: '', //订单号
        id: '',
        charge: '',
        slotsDocType: [{
          values: ['微信', '支付宝'],
          className: 'slot1',
          textAlign: 'center'
        }, ],
        // doctorName: '',
        type: '',
        list: [],
        sentPage: {
          page: 1, //分页累加
        }, //接口入参
        totalNum: 0, //总数据条数
        bottomPullText: "", //上拉提示信息
        allLoaded: false, //分页数据是否已经加载完毕
        swiperImg: [],
        userid: '',
        usertype: '',
        updateShow: false,
        barWidth: 0,
        platform: '',
        apk: '',
      }
    },
    components: {

    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        var that = {
          'page': '1'
        };
        // 每次进入路由执行
        vm.getLiveData();
        vm.justUserType();
        vm.getHotData(that);
        vm.getSwiperImg();
      })
    },
    computed: {

    },
    methods: {
      //去智能诊室
      goImDoctor() {
        if (this.usertype == "doctor") {
          this.$router.push({
            name: 'ImDoctor'
          });
        } else {
          this.$router.push({
            name: 'authentication',
            query: {
              type: 'home'
            }
          });
        }
      },
      //专家会诊
      goDocConsultation() {
        if (this.usertype == "doctor") {
          this.$router.push({
            name: 'docConsultation'
          });
        } else {
          this.$router.push({
            name: 'authentication',
            query: {
              type: 'home'
            }
          });
        }
      },
      // 支付类型选择
      onValuesChangeDocType(picker, values) {
        this.valuesDocType = values[0];
      },
      sureDocType() {
        if (this.valuesDocType == '微信') {
          this.isdocType = false;
          var params = {
            courseid: this.id,
            userid: localStorage.getItem('loginMobile'),
            price: this.charge
          }
          this.$api.post(this.$api.baseURLSchool, "update_user_order/course_order", params, r => {
            if (r.data.ret == 1) {
              const data = {
                order_num: r.data.order_num,
                total_fee: this.charge,
                des: '视频'
              };
              this.$api.post(this.$api.baseURL2, "/android_wxpay", data, r => {
                var params = {
                  partnerid: r.data.mch_id, // merchant id 
                  prepayid: r.data.prepay_id, // prepay id 
                  noncestr: r.data.nonce_str, // nonce 
                  timestamp: r.data.timestamp, // timestamp 
                  sign: r.data.sign, // signed string 
                };
                Wechat.sendPaymentRequest(params, function () {
                  this.$utils._toast('支付成功');
                }, function (reason) {
                  this.$utils._toast(reason);
                });
              }, err => {
                console.log(err);
              }, false, false)
            }
          }, err => {
            console.log(err);
          })


        } else if (this.valuesDocType == '支付宝') {
          //   支付宝支付
          this.isdocType = false;
          var params = {
            courseid: this.id,
            userid: localStorage.getItem('loginMobile'),
            price: this.charge
          }
          this.$api.post(this.$api.baseURLSchool, "update_user_order/course_order", params, r => {
            if (r.data.ret == 1) {
              const data = {
                order_num: r.data.order_num,
                amount: this.charge,
                subject: '视频'
              };
              this.$api.post(this.$api.baseURL2, "/alipay_app", data, r => {
                var params = r.data.data;
                cordova.plugins.alipay.payment(params, function () {
                  this.$utils._toast('支付成功');
                }, function (reason) {
                  this.$utils._toast(reason);
                });
              }, err => {
                console.log(err);
              }, false, false)
            }
          }, err => {
            console.log(err);
          })
        }
      },
      // 登录拦截
      isLogin() {
        this.userid = localStorage.getItem("loginMobile");
        if (!this.userid) {
          this.$router.push('/login1')
          return false;
        } else {
          return true;
        }
      },
      goNext(item) {
        if (item.iffree == 'charge' && item.charge != 0) {
          this.$api.get(this.$api.baseURLSchool, "view_detail/course_order?userid=" + localStorage.getItem(
              'loginMobile') +
            "&courseid=" + item.id + "", {}, r => {
              if (r.data.ret == 1) {
                if (r.data.info.status == 'pay') {
                  this.$router.push({
                    name: 'homeDetail',
                    query: {
                      id: item.id,
                      poster: item.course_pic
                    }
                  });
                } else {
                  this.id = item.id;
                  this.charge = item.charge;
                  this.isdocType = true;
                }
              } else if (r.data.ret == 0) {
                var params = {
                  courseid: item.id,
                  userid: localStorage.getItem('loginMobile'),
                  price: item.charge
                }
                this.id = item.id;
                this.charge = item.charge;
                this.isdocType = true;
              }
            }, err => {
              console.log(err);
            })
        } else {
          this.$router.push({
            name: 'homeDetail',
            query: {
              id: item.id,
              poster: item.course_pic
            }
          });
        }
      },
      //热门视频
      getLiveData(params) {
        this.$api.post(this.$api.baseURLSchool, "selecttype_view/view_live_room_user/0?subtype=hot", params, r => {
          this.list1 = r.data.rows;
          if (r.data.ret == -3) {
            this.isLogin()
          }
        }, err => {
          console.log(err);
        })
      },

      //记录滚动位置
      setScrollTop(e) {
        localStorage.setItem("scrollTop", e.target.scrollTop);
      },
      justUserType() { //判断用户是否通过医生认证
        if (localStorage.getItem("loginMobile")) {
          this.userid = localStorage.getItem("loginMobile");
          if (localStorage.getItem("type") != null) {
            if (localStorage.getItem("type") != '') {
              this.usertype = JSON.parse(localStorage.getItem("type"))
            } else {
              this.$api.get(this.$api.baseURLSchool, "select_cid/user/" + this.userid, {}, r => {
                if (r.data.ret == -3) {
                  localStorage.clear();
                  this.isLogin()
                }
                if (r.data.ret == 1) {
                  if (r.data.info.type) {
                    this.usertype = r.data.info.type;
                  }
                }
              }, err => {
                console.log(err);
              })
            }
          } else {
            this.$api.get(this.$api.baseURLSchool, "select_cid/user/" + this.userid, {}, r => {
              if (r.data.ret == 1) {
                if (r.data.info.type) {
                  this.usertype = r.data.info.type;
                }
              }
            }, err => {
              console.log(err);
            })
          }

        }
      },
      //搜索课程
      goSearch() {
        this.$router.push({
          name: 'searchCourse'
        });
      },
      download() {
        this.platform = device.platform;
        var that = this
        var url = this.apk;
        var targetPath = '';

        if (this.platform == 'Android') {
          targetPath = cordova.file.externalDataDirectory + "/bim123.apk";
        }
        //APP下载存放的路径，可以使用cordova file插件进行相关配置 cordova.file.dataDirectory
        var trustHosts = true;
        var options = {};
        var ft = new FileTransfer();
        //监听下载进度
        ft.onprogress = function (e) {
          if (e.lengthComputable) {
            that.barWidth = parseInt((e.loaded / e.total) * 100);
          }
        }
        ft.download(url, targetPath, function (entry) {
          that.updateShow = false
          // android打开安装
          if (that.platform == 'Android') {
            var target = entry.fullPath;
            cordova.plugins.fileOpener2.showOpenWithDialog(entry.toInternalURL(),
              'application/vnd.android.package-archive', {
                success: function () {
                  alert('安装成功');
                },
                error: function (e) {
                  alert('安装失败');
                }

              });
          } else if (that.platform == 'iOS') {
            // 加载其他应用，应用在升级的时候，iOS使用openURL打开、Android使用open打开  'tel://10086'
            cordova.plugins.fileOpener2.openURL(entry.toURL(), {
              success: function () {
                alert('成功');
              },
              error: function (e) {
                alert('失败');
              }
            });
          }
        }, function (err) {
          alert("下载失败！");
        }, true, );
      },
      //获取课程列表
      getHotData(params) {
        // 第一个参数是root--baseurl
        var that = this;
        this.$api.post(this.$api.baseURLSchool, "selecttype_view/view_course_user/0?course_type=-1", params, r => {
          this.totalNum = r.data.records; //总数据
          if (this.sentPage.page == 1) {
            that.list = r.data.rows;
          } else {
            that.list = that.list.concat(r.data.rows);
          }
          if (r.data.rows.length == 0 && this.sentPage.page > 1) {
            that.$utils._toast("暂无更多数据");
          }
        }, err => {
          console.log(err);
        })
      },
      //获取轮播图
      getSwiperImg() {
        this.$api.get(this.$api.baseURLSchool, "selectdata2/config?category=lunbo", {}, r => {
          if (r.data.ret == 1) {
            this.swiperImg = r.data.info;
            var mySwiper = new Swiper('.swiper-container', {
              autoplay: 2000,
              autoplayDisableOnInteraction: false,
              loop: false,
              pagination: '.swiper-pagination',
              initialSlide: 0,
              observer: true,
              observeParents: true,
            });

          }
        }, err => {
          console.log(err);
        })
      },
      //上拉加载
      loadBottom() {
        (this.sentPage.page) ++;
        setTimeout(() => {
          this.getHotData(this.sentPage);
        }, 20);
        if (this.totalNum == this.list.length) {
          this.allLoaded = true;
        }
        this.$refs.loadmore.onBottomLoaded();
      },
      init() {
        //医生信息
        this.$api.get(this.$api.baseURLSchool, "select_cid/doctor/" + localStorage.getItem("loginMobile"), {}, r => {
          if (r.data.ret == 0) {} else if (r.data.ret == 1) {
            localStorage.setItem('doctorName', r.data.info.name)
            // this.doctorName = r.data.info.name
          }
        }, err => {
          console.log(err);
        })

      },
      //下载更新
      update() {
        this.$api.post(this.$api.baseURLSchool, "/admin/version_pro/no_token/1", {}, r => {
          if (r.data.ret == 1) {
            this.apk = r.data.info.url;
            this.newVersion = r.data.info.versionCode;
            if (this.newVersion > 112) {
              this.updateShow = true
            } else {
              this.updateShow = false
            }
          }
          if (r.data.ret == -3) {
            localStorage.clear();
            this.isLogin()
          }
        }, err => {
          console.log(err);
        }, false, false)
      },
      // 是否下载
    },
    created() {
      this.update();
      this.justUserType();
      this.getLiveData();
      this.getHotData(this.sentPage);
      this.getSwiperImg();
      this.init();
      this.isLogin();
    },
    mounted() {
      //   var h = Math.ceil(parseInt($('.zhibo').css('height')) / 192)
      //   var w = h * (100) + '%';
      //   $('.zhibo').css('width', w)
      //   $('.zhibo').css('min-width', '100%')
      this.getSwiperImg();
    },
    activated() {
      this.justUserType();
      this.getLiveData();
      this.getHotData(this.sentPage);
      this.getSwiperImg();
      this.init();
      this.isLogin();
    },
  }

</script>

<style lang="scss" scoped>
  @import "../css/swiper.min.css";
  @import "../css/scss/home/home.css";

  .discount {
    height: 25px;
    width: 50px;
    line-height: 25px;
    border-radius: 13px;
    display: block;
    text-align: center;
    font-size: 12px;
  }

  .zhibo {
    left: 100%;
    width: 100%;
    position: absolute;
    top: 0.4rem;
    z-index: 50;
    animation: danmu 20s linear infinite;

  }

  @keyframes danmu {
    from {
      left: 70%;
      transform: translateX(0);
    }

    to {
      left: 0;
      transform: translateX(-100%);
    }
  }

  .zhibo ul li {
    width: 100px;
    height: 20px;
    line-height: 20px;
    border-radius: 5px;
    color: #fff;
    padding-left: 5px;
    margin: 5px;
    float: left;
    text-align: center;
  }

  .mc1 {
    padding: 40px 0;

    img {
      display: block;
      margin: 0 auto;
    }

    p {
      padding-top: 10px;
      text-align: center;
    }
  }

  .mc {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .5);
    z-index: 99;

    .duration {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 235px;
      background: #fff;

      div.top {
        display: flex;
        height: 45px;
        line-height: 45px;
        background: linear-gradient(to right, #54a589, #68c6a5);
        padding: 0 25px;

        a {
          flex: 1;
          font-size: 14px;
          color: #fff;

          &:last-child {
            text-align: right;
          }
        }
      }
    }
  }

  s {
    margin-left: 8px;
    font-size: .12rem;
    color: rgba(156, 156, 156, 1);
  }


  .search {
    height: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  .icon-info {
    width: 0.35rem;
    height: 0.35rem;
    margin-right: 0.1rem;
  }

  .icon-info img,
  .icon-logo img {
    width: 100%;
    height: 100%;
  }

  .icon-logo {
    /* width: 0.35rem;
      height: 0.35rem; */
    margin-left: 0.1rem;
  }

  #clinic1,
  #clinic2,
  #clinic3,
  #clinic4 {
    width: 50%;
    background-size: 100%;

  }


  #clinic1 {
    background: url('../image/clinic1.png') no-repeat center;
  }

  #clinic2 {
    background: url('../image/clinic2.png') no-repeat center;
  }

  #clinic3 {
    background: url('../image/clinic3.png') no-repeat center;
  }

  #clinic4 {
    background: url('../image/clinic4.png') no-repeat center;
  }

  .Update {
    background: rgba(0, 0, 0, 0.3);
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  .content {
    width: 288px;
    height: 331px;
    position: relative;
  }

  .content image {
    width: 100%;
    height: 100%;
    position: absolute;
  }

  .down {
    width: 185px;
    height: 43px;
    background: #54a589;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    text-align: center;
    line-height: 43px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 33px;
  }

  .progress {
    width: 225px;
    height: 6px;
    border-radius: 10px;
    background: rgba(238, 238, 238, 1);
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);



    .bar {
      height: 6px;
      max-width: 225px;
      border-radius: 10px;
      background: #43c4da;
    }
  }

  .progress1 {
    width: 100%;
    text-align: center;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%)
  }

</style>
